﻿#include "NamedPipeClient.h"

int main(int argc, char * argv)
{
	OpenNamedPipeInClient();

	//Receive data from server
	NamedPipeReadInClient();

	//Write data to named pipe
	NamedPipeWriteInClient();

	system("pause");
}


void OpenNamedPipeInClient()
{
	//Wait to connect to named pipe
	if(!WaitNamedPipe(pPipeName, NMPWAIT_WAIT_FOREVER))
	{
		cout<<"Named pipe instance not exists..."<<endl<<endl;
		return;
	}

	//Open named pipe
	hNamedPipe = CreateFile(pPipeName, GENERIC_READ | GENERIC_WRITE, 
		0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if(INVALID_HANDLE_VALUE == hNamedPipe)
	{
		cout<<"Open named pipe failed"<<endl<<endl;
		return;
	}
}


void NamedPipeReadInClient()
{
	TCHAR *                pReadBuf;
	DWORD                dwRead;

	pReadBuf = new TCHAR[_tcslen(pStr) + 1];
	memset(pReadBuf, 0, _tcslen(pStr) + 1);

	//Read data from named pipe
	if(!ReadFile(hNamedPipe, pReadBuf, _tcslen(pStr), &dwRead, NULL))
	{
		delete []pReadBuf;

		cout<<"Read data failed..."<<endl<<endl;
		return;
	}
	cout<<"Read data success:    "<<pReadBuf<<endl<<endl;
}


void NamedPipeWriteInClient()
{
	DWORD                dwWrite;

	//Write to named pipe
	if(!WriteFile(hNamedPipe, pStr, _tcslen(pStr), &dwWrite, NULL))
	{
		cout<<"Write to named pipe failed..."<<endl<<endl;
		return;
	}
	cout<<"Write to named pipe success:    "<<pStr<<endl<<endl;
}